import axios from 'axios'

const ERR_OK = 0

export function post(url, param = []) {
  configAxios()
  return new Promise((resolve, reject) => {
    axios.post(url, param)
      .then((res) => {
        if (res.errno === ERR_OK) {
          resolve(res.data)
        } else {
          reject(getError(res.errno, res.msg))
        }
      }).catch(error => {
        reject(error)
      })
  })
}

export function get(url, param = []) {
  configAxios()
  return new Promise((resolve, reject) => {
    axios.get(url, param)
      .then(res => {
        if (res.data.errno === ERR_OK) {
          resolve(res.data.data)
        } else {
          console.log('success', 'res: ' + res.data.errno)
          reject(getError(res.data.errno, res.msg))
        }
      }).catch(error => {
        console.log('error', 'error: ' + error)
        reject(error)
      })
  })
}

function configAxios() {
  axios.defaults.baseURL = getHost()
}

function getHost() {
  return '/api'
}

function getError(code, msg) {
  return {
    'code': code,
    'msg': msg
  }
}
